package com.qing.expert.modules.notification.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qing.expert.modules.notification.entity.Notification;
import com.qing.expert.modules.notification.mapper.NotificationMapper;
import com.qing.expert.modules.notification.service.NotificationService;
import com.qing.expert.modules.notification.vo.response.NotificationVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class NotificationServiceImpl implements NotificationService {

    @Resource
    private NotificationMapper notificationMapper;

    @Override
    public List<NotificationVO> getNotificationList(String userId) {
        // 查询通知列表
        List<Notification> list = notificationMapper.selectList(
                new LambdaQueryWrapper<Notification>()
                        .eq(Notification::getUserId, userId)
                        .orderByDesc(Notification::getCreateTime));

        // 转换为VO对象
        List<NotificationVO> voList = new ArrayList<>();
        for (Notification notification : list) {
            NotificationVO vo = new NotificationVO();
            BeanUtils.copyProperties(notification, vo);
            // 设置时间描述
            vo.setCreateTimeDesc(getTimeDesc(notification.getCreateTime()));
            voList.add(vo);
        }

        return voList;
    }

    @Override
    public void markAsRead(String userId, String notificationId) {
        Notification notification = notificationMapper.selectById(notificationId);
        if (notification != null && notification.getUserId().equals(userId)) {
            notification.setIsRead(1);
            notificationMapper.updateById(notification);
        }
    }

    @Override
    public void markAllRead(String userId) {
        notificationMapper.markAllRead(userId);
    }

    @Override
    public Integer getUnreadCount(String userId) {
        Long count = notificationMapper.selectCount(
                new LambdaQueryWrapper<Notification>()
                        .eq(Notification::getUserId, userId)
                        .eq(Notification::getIsRead, 0));
        return count.intValue();
    }

    /**
     * 获取时间描述
     */
    private String getTimeDesc(LocalDateTime time) {
        LocalDateTime now = LocalDateTime.now();
        long minutes = java.time.Duration.between(time, now).toMinutes();
        if (minutes < 60) {
            return minutes + "分钟前";
        }
        long hours = minutes / 60;
        if (hours < 24) {
            return hours + "小时前";
        }
        return DateUtil.format(java.util.Date.from(time.atZone(java.time.ZoneId.systemDefault()).toInstant()),
                "MM-dd HH:mm");
    }
}